<template>
  <div>
    <!--  搜索栏  -->
    <div style="margin-bottom: 20px;margin-top: 20px">
      <el-input v-model="searchName" placeholder="请输入商品名"
                suffix-icon="el-icon-search" style="width: 200px;"
                @keyup.enter.native="loadPost"></el-input>

      <el-select style="margin-left: 15px" v-model="storage" placeholder="请选择仓库">
        <el-option
            v-for="(item,index) in storageData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <el-select style="margin-left: 15px" v-model="goodstype" placeholder="请选择分类">
        <el-option
            v-for="item in goodstypeData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <el-button type="primary" style="margin-left: 10px" @click="loadPost">查询</el-button>
      <el-button type="success" style="margin-left: 10px" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="add" v-if="user.roleId!=2">+ 新增商品</el-button>
      <el-button type="warning" style="margin-left: 10px" @click="inGoods" v-if="user.roleId!=2">◆ 商品入库 ◆</el-button>
      <el-button type="danger" style="margin-left: 10px" @click="outGoods" v-if="user.roleId!=2">◆ 商品出库 ◆</el-button>
    </div>

    <!--  表格  -->
    <el-table :data="tableData" stripe border highlight-current-row
              :header-cell-style="{background:'#f3f6fd',color:'#555','text-align':'center'}"
              :cell-style="{'text-align':'center'}" @current-change="handleCurrentChange1"
    >
      <el-table-column prop="id" label="ID" width="80">
      </el-table-column>
      <el-table-column prop="name" label="商品名" width="220">
      </el-table-column>
      <el-table-column prop="storage" label="所属仓库" width="100" :formatter="formatStorage">
      </el-table-column>
      <el-table-column prop="goodstype" label="商品分类" width="100" :formatter="formatGoodsType">
      </el-table-column>
      <el-table-column prop="count" label="数量" width="80">
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="auto">
      </el-table-column>
      <el-table-column prop="operate" label="操作" v-if="user.roleId!=2">
        <template slot-scope="scop">
          <el-button type="primary" size="small" round @click="upd(scop.row)">编辑</el-button>
          <!--删除气泡框-->
          <el-popconfirm
              title="您确定要删除该条商品信息吗？"
              @confirm="del(scop.row.id)"
          >
            <el-button slot="reference" type="danger" size="small" round
                       style="margin-left: 15px">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--  分页  -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[ 5, 10, 20, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!--  对话框用于新增功能  -->
    <el-dialog
        title="新增商品"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
      <el-form :rules="rules" ref="form" :model="form" label-width="100px">
        <el-form-item label="商品名：" prop="name">
          <el-col :span="25">
            <el-input v-model="form.name"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="所属仓库:" prop="storage">
          <el-col :span="25">
            <el-select v-model="form.storage" placeholder="请选择仓库">
              <el-option
                  v-for="(item,index) in storageData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="商品分类：" prop="goodstype">
          <el-col :span="25">
            <el-select v-model="form.goodstype" placeholder="请选择分类">
              <el-option
                  v-for="item in goodstypeData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="数量：" prop="count">
          <el-col :span="25">
            <el-input v-model="form.count"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-col :span="25">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save  ">确 定</el-button>
    </span>
    </el-dialog>

    <!--  对话框用于入库功能  -->
    <el-dialog
        title="商品出入库"
        :visible.sync="inDialogVisible"
        width="30%"
        center>
      <el-dialog
          width="70%"
          title="用户选择"
          :visible.sync="innerVisible"
          append-to-body>
        <SelectUser @doSelectUser="doSelectUser" ref="child"></SelectUser>
        <span slot="footer" class="dialog-footer">
          <el-button @click="restParam">取 消</el-button>
          <el-button type="primary" @click="confirmUser">确 定</el-button>
        </span>
      </el-dialog>
      <el-form :rules="rules1" ref="form1" :model="form1" label-width="100px">
        <el-form-item label="商品名：">
          <el-col :span="25">
            <el-input v-model="form1.goodsname" readonly></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="申请人：">
          <el-col :span="25">
            <el-input v-model="form1.username" readonly @click.native="selectUser"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="数量：" prop="count">
          <el-col :span="25">
            <el-input v-model="form1.count"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-col :span="25">
            <el-input type="textarea" v-model="form1.remark"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="inDialogVisible = false" >取 消</el-button>
    <el-button type="primary" @click="doIn">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import SelectUser from "@/components/user/SelectUser";

export default {
  name: "GoodsMange",
  components: {SelectUser},
  data() {
    let checkCount = (rule, value, callback) => {
      if (value > 9999) {
        callback(new Error('输入数量过大'));
      } else {
        callback();
      }
    };

    return {
      goodstypeData: [],
      storageData: [],
      tableData: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      storage: '',
      goodstype: '',
      searchName: '',
      centerDialogVisible: false,
      inDialogVisible: false,
      innerVisible: false,
      currentRow: {},
      tempUser:{},
      user: JSON.parse(sessionStorage.getItem('CurUser')),
      form: {
        id: '',
        name: '',
        storage: '',
        goodstype: '',
        count: '',
        remark: ''
      },
      form1: {
        goods: '',
        goodsname: '',
        count: '',
        username: '',
        userid: '`',
        adminId: '',
        remark: '',
        action:'1'
      },
      rules1: {
        count: [
          {required: true, message: '请输入数量', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数', trigger: 'blur'},
          {validator: checkCount, trigger: 'blur'}
        ]
      },
      rules: {
        goodstype: [
          {required: true, message: '请选择商品所属仓库', trigger: 'blur'},
        ],
        storage: [
          {required: true, message: '请选择商品分类', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入商品名', trigger: 'blur'},
        ],
        count: [
          {required: true, message: '请输入数量', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数', trigger: 'blur'},
          {validator: checkCount, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    //仓库id转为仓库名
    formatStorage(row) {
      let temp = this.storageData.find(item => {
        return item.id == row.storage
      })
      return temp && temp.name;
    },
    //分类id转商品分类
    formatGoodsType(row) {
      let temp = this.goodstypeData.find(item => {
        return item.id == row.goodstype
      })
      return temp && temp.name;
    },
    //分页查询数据
    loadPost() {
      this.$axios.post(this.$httpUrl + '/goods/listPage', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        param: {
          name: this.searchName,
          goodstype: this.goodstype + '',
          storage: this.storage + ''
        }
      }).then(res => {
        console.log(res)
        if (res.data.code == 200) {
          this.tableData = res.data.data;
          this.total = res.data.total
        } else {
          alert('获取数据失败')
        }
      })
    },
    loadStorage() {
      this.$axios.get(this.$httpUrl + '/storage/list').then(res => res.data).then(res => {
        if (res.code == 200) {
          this.storageData = res.data;
        } else {
          alert('获取数据失败')
        }
      })
    },
    loadGoodsType() {
      this.$axios.get(this.$httpUrl + '/goodstype/list').then(res => res.data).then(res => {
        if (res.code == 200) {
          this.goodstypeData = res.data;
        } else {
          alert('获取数据失败')
        }
      })
    },
    restParam(){
      this.innerVisible = false
      this.$refs.child.resetParam();
    },
    handleCurrentChange1(val) {
      this.currentRow = val;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1
      this.pageSize = val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      this.loadPost()
    },
    resetParam() {
      this.searchName = '';
      this.storage = ''
      this.goodstype = ''
    },
    doSelectUser(val){
      this.tempUser = val;
    },
    confirmUser(){
      this.form1.username=this.tempUser.name;
      this.form1.userid=this.tempUser.id;
      this.innerVisible=false;
    },
    selectUser() {
      this.innerVisible = true;
    },
    outGoods(){
      if (!this.currentRow.id) {
        alert('请选中商品')
        return;
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm();
        this.form1.username = '';
      })
      this.form1.goodsname = this.currentRow.name;
      this.form1.goods = this.currentRow.id;
      this.form1.adminId = this.user.id;
      this.form1.action='2'
    },
    inGoods() {
      if (!this.currentRow.id) {
        alert('请选中商品')
        return;
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm();
        this.form1.username = '';
      })
      this.form1.goodsname = this.currentRow.name;
      this.form1.goods = this.currentRow.id;
      this.form1.adminId = this.user.id;
      this.form1.action='1  '  //1为入库操作  2为出库操作

    },
    resetInForm() {
      this.$refs.form1.resetFields();
    },
    add() {
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.resetForm();
      })
    },
    upd(row) {
      //显示编辑框
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        //将修改的数据回显在表单上
        this.form.id = row.id
        this.form.name = row.name
        this.form.storage = row.storage
        this.form.goodstype = row.goodstype
        this.form.count = row.count
        this.form.remark = row.remark
      })

    },
    doIn() {
      this.$axios.post(this.$httpUrl + '/record/add', this.form1).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message({
            showClose: true,
            message: '恭喜你，商品出入库成功',
            type: 'success'
          });
          this.inDialogVisible = false;
          this.loadPost()
          this.resetInForm()
        } else {
          this.$message({
            showClose: true,
            message: '出错了，商品出 入库失败',
            type: 'error'
          });
        }
      })
    },
    doadd() {
      this.$axios.post(this.$httpUrl + '/goods/add', this.form).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message({
            showClose: true,
            message: '恭喜你，商品新增成功',
            type: 'success'
          });
          this.centerDialogVisible = false;
          this.loadPost()
          this.resetForm()
        } else {
          this.$message({
            showClose: true,
            message: '出错了，商品新增失败',
            type: 'error'
          });
        }
      })
    },
    doupd() {
      this.$axios.put(this.$httpUrl + '/goods/update', this.form).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message({
            showClose: true,
            message: '商品修改成功',
            type: 'success'
          });
          this.centerDialogVisible = false;
          this.loadPost()
        } else {
          this.$message({
            showClose: true,
            message: '商品修改失败',
            type: 'error'
          });
        }
      })
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.doupd();
          } else {
            this.doadd();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    resetForm() {
      this.$refs.form.resetFields();
      this.form.id = '';
    },
    del(id) {
      this.$axios.delete(this.$httpUrl + '/goods/delete/' + id).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.loadPost()
        } else {
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'error'
          });
        }
      })
    }

  },
  beforeMount() {
    this.loadStorage();
    this.loadGoodsType();
    this.loadPost();
  }
}
</script>

<style scoped>


</style>